const { DataTypes } = require('sequelize')

module.exports = (sequelize) => {
  const File = sequelize.define('File', {
    id: {
      type: DataTypes.BIGINT.UNSIGNED,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      comment: '用户ID'
    },
    original_name: {
      type: DataTypes.STRING(255),
      allowNull: false,
      comment: '原始文件名'
    },
    file_name: {
      type: DataTypes.STRING(255),
      allowNull: false,
      comment: '存储文件名'
    },
    file_path: {
      type: DataTypes.STRING(500),
      allowNull: false,
      comment: '文件存储路径'
    },
    file_size: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '文件大小(字节)'
    },
    file_type: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '文件MIME类型'
    },
    file_extension: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: '文件扩展名'
    },
    file_url: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '文件访问URL'
    },
    preview_url: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '预览图URL'
    },
    page_count: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '文档页数'
    },
    metadata: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '文件元数据'
    },
    status: {
      type: DataTypes.TINYINT,
      allowNull: false,
      defaultValue: 1,
      comment: '状态: 0-已删除, 1-正常'
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '创建时间'
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '更新时间'
    }
  }, {
    tableName: 'files',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        name: 'idx_user_id',
        fields: ['user_id']
      },
      {
        name: 'idx_status',
        fields: ['status']
      },
      {
        name: 'idx_created_at',
        fields: ['created_at']
      }
    ]
  })

  File.associate = (models) => {
    File.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user'
    })
  }

  return File
}